package database;

import entity.Semester;
import manager.SemesterManager;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Noi
 */
public class SemesterManagerDB {

    private CallableStatement cstmt;
    private java.sql.Connection conn;
    private ResultSet rs;

    public SemesterManagerDB(java.sql.Connection conn) {
        this.conn = conn;
    }

    public void loadData(SemesterManager semesterManager) {
        try {
            cstmt = conn.prepareCall("{call sp_GetSemester}");
            rs = cstmt.executeQuery();
            while (rs.next()) {
                int semesterID = rs.getInt("SemesterID");
                String semesterName = rs.getString("SemesterName");
                boolean status = rs.getBoolean("Status");
                Semester semester = new Semester(semesterID, semesterName,status);
                semesterManager.add(semester);
            }
            rs.close();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(SemesterManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void deleteSemester(Semester obj) {
        try {
            cstmt = conn.prepareCall("{call sp_DeleteSemester(?)}");
            cstmt.setInt(1, obj.getSemesterID());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(SemesterManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void insertSemester(Semester obj) {
        try {
            cstmt = conn.prepareCall("{call sp_InsertSemester(?,?)}");
            cstmt.registerOutParameter(1, Types.INTEGER);
            cstmt.setString(2, obj.getSemesterName());
            cstmt.executeUpdate();
            obj.setSemesterID(cstmt.getInt("SemesterID"));
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(SemesterManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateSemester(Semester obj) {
        try {
            cstmt = conn.prepareCall("{call sp_UpdateSemester(?,?,?)}");
            cstmt.setInt(1, obj.getSemesterID());
            cstmt.setString(2, obj.getSemesterName());
            cstmt.setBoolean(3, obj.isStatus());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(SemesterManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
